package com.imagination.applet.domain.user_topic.service.impl;

import com.imagination.applet.controller.web.configuration.UserHolder;
import com.imagination.applet.domain.topic.model.Topic;
import com.imagination.applet.domain.topic.repository.TopicRepository;
import com.imagination.applet.domain.user.model.User;
import com.imagination.applet.domain.user.repository.UserRepository;
import com.imagination.applet.domain.user.service.UserService;
import com.imagination.applet.domain.user_topic.model.UserTopic;
import com.imagination.applet.domain.user_topic.repository.UserTopicRepository;
import com.imagination.applet.domain.user_topic.service.UserTopicService;
import com.imagination.applet.infrastructure.handler.ServiceException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;


@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class UserTopicServiceImpl implements UserTopicService {

    private final UserTopicRepository userTopicRepository;

    private final UserService userService;

    private final UserRepository userRepository;

    private final TopicRepository topicRepository;

    @Override
    @Transactional
    public void buyTopic(Long topicId) {

        Long userId = UserHolder.getUserId();
//        Long userId = 10000015L;

        Optional<User> user = userService.getByUserId(userId);

        Optional<Topic> byId = topicRepository.findById(topicId);


        // 账户消费星星
        if(user.isPresent()){
            User update = user.get();
            int start = update.getStarCount() - byId.get().getFee();
            if(start < 0){
                throw new ServiceException("星星余额不足!");
            }
            update.setStarCount(start);
            userRepository.saveAndFlush(update);
        }

        UserTopic userTopic = new UserTopic();
        userTopic.setUserId(userId);
        userTopic.setTopicId(topicId);

        long count = userTopicRepository.count(Example.of(userTopic));
        if(count>0){
            throw new ServiceException("该分类已购买不可重复购买");
        }

        userTopicRepository.save(userTopic);
    }
}
